package com.kkks.spring_rest.tick.component.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kkks.spring_rest.tick.component.BaseComponent;
import com.kkks.spring_rest.tick.dao.HibernateTemplateBaseDao;
import com.kkks.spring_rest.tick.model.WhoUsers;
import com.kkks.spring_rest.tick.utils.ThreeDESHelper;

/**
 * 公有方法的实现类
 * 
 * @author SC
 * @version 1.0
 * @created 2012-7-18 下午1:47:59
 * @describe
 */
@Component("baseComponent")
@Transactional
@SuppressWarnings("rawtypes")
public class BaseComponentImpl implements BaseComponent {

	@Autowired
	private HibernateTemplateBaseDao hibernateTemplateBaseDao;

	public HibernateTemplateBaseDao getHibernateTemplateBaseDao() {
		return hibernateTemplateBaseDao;
	}

	public void setHibernateTemplateBaseDao(
			HibernateTemplateBaseDao hibernateTemplateBaseDao) {
		this.hibernateTemplateBaseDao = hibernateTemplateBaseDao;
	}

	/**
	 * 验证用户Id 以及 用户编码
	 * 
	 * @param userId
	 * @param userToken
	 * @return boolean
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public boolean validUserToken(String userId, String userToken) {// TODO
		boolean flag = false;
		try {
			WhoUsers whoUsers = (WhoUsers) this.hibernateTemplateBaseDao
					.findById(WhoUsers.class, Integer.parseInt(userId));
			if (whoUsers != null) {
				String origion = ThreeDESHelper.decryptMode(java.net.URLDecoder
						.decode(userToken, "utf-8"));
				String userNameandId = whoUsers.getUserName()
						+ whoUsers.getUserId();
				if (origion.equals(userNameandId)) {
					flag = true;
				} else {
					flag = false;
				}
			} else {
				flag = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 判断用户名Email是否存在
	 * 
	 * @param userName
	 *            用户名Email
	 * @return 存在true， 不存在false
	 */
	public boolean isExistUserNameEmail(String userName) {
		boolean result = false;
		try {
			List userList = this.hibernateTemplateBaseDao.findListByHql(
					" from WhoUsers where userName = ? or email = ?",
					new Object[] { userName, userName });

			if (userList.size() > 0) {
				result = true;
			} else {
				result = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
